package com.ubs.training.server.dao.impl.hbm;

import com.ubs.training.server.dao.RatingDao;
import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.dao.model.Rating;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/27/12
 * Time: 3:18 AM
 * To change this template use File | Settings | File Templates.
 */

@Repository("hbmRatingDao")
public class HbmRatingDao implements RatingDao {

    private SessionFactory factory;

    private HibernateTemplate tpl;

    public SessionFactory getFactory() {
        return factory;
    }

    @Autowired
    public void setFactory(SessionFactory factory) {
        tpl = new HibernateTemplate(factory);
        this.factory = factory;
    }

    @Override
    public List<Rating> getAll() {
        return tpl.loadAll(Rating.class);
    }

    @Override
    public List<Rating> getByClientID(int clientID) {
        Session session = getFactory().getCurrentSession();
        List ratings;
        Client client = new Client();
        client.setId(clientID);
        return tpl.findByCriteria(DetachedCriteria.forClass(Rating.class).add(Property.forName("ClientID").eq(clientID)));
    }

    @Override
    public Rating getById(int id) {
        return tpl.get(Rating.class, id);
    }

    @Override
    public void add(Rating rating) {

        tpl.save(rating);
//        tpl.evict(rating);
    }

    @Override
    public void update(Rating rating) {
//        tpl.merge(rating);
        tpl.update(rating);

    }

    @Override
    public boolean delete(Rating rating) {
//        tpl.merge(rating);
        tpl.delete(rating);
        return true;
    }
}
